package com.maikang.exammall.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.log4j.Log4j2;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Hashtable;

import static com.maikang.exammall.entity.constant.ImageSizeConstant.LOGO_INSIDE_QRCODE_LENGTH;
import static com.maikang.exammall.entity.constant.ImageSizeConstant.QRCODE_LENGTH;

/**
 * QRCodeUtil 生成二维码工具类
 */

@Log4j2
public class QRCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";

    public static BufferedImage createImageWithDefaultLogo(String content) throws Exception {
        final InputStream mkLogoInputStream = new BufferedInputStream(QRCodeUtil.class.getClassLoader().getResourceAsStream("static/image/logo32x32.jpg"));
        return createImage(content, mkLogoInputStream, true);
    }

    public static BufferedImage createImage(String content, InputStream logoInputStream, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_LENGTH, QRCODE_LENGTH,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoInputStream == null) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertLogoToCenter(image, ImageIO.read(logoInputStream), needCompress);
        return image;
    }

    public static void insertLogoToCenter(BufferedImage source, Image logo , boolean needCompress) throws Exception {
        int width = logo.getWidth(null);
        int height = logo.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > LOGO_INSIDE_QRCODE_LENGTH) {
                width = LOGO_INSIDE_QRCODE_LENGTH;
            }
            if (height > LOGO_INSIDE_QRCODE_LENGTH) {
                height = LOGO_INSIDE_QRCODE_LENGTH;
            }
            Image image = logo.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            logo = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_LENGTH - width) / 2;
        int y = (QRCODE_LENGTH - height) / 2;
        graph.drawImage(logo, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String destPath) throws Exception {
        BufferedImage image = QRCodeUtil.createImageWithDefaultLogo(content);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }
}